import os
import re

import click
import pandas as pd


@click.command()
@click.argument("sheets", nargs=-1, required=True)
@click.option("-o", "--output", help="output folder", required=True)
def main(sheets, output):
    """Parse tags from Excel sheets and save to output files."""
    dfs = [pd.read_excel(sheet) for sheet in sheets]
    shebao = pd.concat(dfs, ignore_index=True)

    all_level_1 = set()
    all_level_2 = set()
    all_scene = set()
    all_keywords = set()

    for _, row in shebao.iterrows():
        tags = row["tag"] if "tag" in row else row["标签"]
        if not isinstance(tags, str):
            continue

        tags = [
            line.strip()
            for line in tags.split("\n")
            if line.strip() and isinstance(line, str)
        ]

        level_1 = []
        level_2 = []
        scene = []
        keywords = []
        for tag in tags:
            if re.match(r"一级事项引导[：:]", tag):
                cur_level_1 = re.split(r"[,，]", re.sub(r"一级事项引导[：:]", "", tag))
                level_1.extend([item.strip() for item in cur_level_1 if item])

            if re.match(r"二级事项引导[：:]", tag):
                level_2.extend(
                    re.split(r"[,，]", re.sub(r"二级事项引导[：:]", "", tag))
                )

            if re.match(r"场景引导[：:]", tag):
                scene.extend(re.split(r"[,，]", re.sub(r"场景引导[：:]", "", tag)))

            if re.match(r"关键词[：:]", tag):
                keywords.extend(re.split(r"[,，、]", re.sub(r"关键词[：:]", "", tag)))

        all_level_1.update([item for item in level_1 if item])
        all_level_2.update([item for item in level_2 if item])
        all_scene.update([item for item in scene if item])
        all_keywords.update([item for item in keywords if item])

    # write tags to file
    with open(os.path.join(output, "level_1.txt"), "w") as f:
        f.write("\n".join(all_level_1))

    with open(os.path.join(output, "level_2.txt"), "w") as f:
        f.write("\n".join(all_level_2))

    with open(os.path.join(output, "scene.txt"), "w") as f:
        f.write("\n".join(all_scene))

    with open(os.path.join(output, "keywords.txt"), "w") as f:
        f.write("\n".join(all_keywords))


if __name__ == "__main__":
    main()
